import asyncio
import cv2
import numpy as np

width = 1280
height = 720

loops = asyncio.new_event_loop()

buffer = asyncio.Queue(50, loop=loops)


async def decodeVideo():
    stream = await asyncio.create_subprocess_shell(
        f"ffmpeg -f mp4 -i test2.mp4 -f rawvideo -pix_fmt bgr24 -",
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
        shell=True
    )
    while True:
        print("开始读取")
        rawData = await stream.stdout.readexactly(width * height * 3)
        print("读取结束")
        await buffer.put(rawData)


async def showVideo():
    while True:
        if not buffer.empty():
            rawData = await buffer.get()
            frame = np.frombuffer(rawData, np.uint8).reshape([height, width, 3])
            cv2.imshow("imshow", frame)
            cv2.waitKey(1)
            await asyncio.sleep(0)
        else:
            print("Buffer空")
            await asyncio.sleep(0)


async def main():
    await asyncio.gather(decodeVideo(), showVideo(), loop=loops)

loops.run_until_complete(main())